% This function uses svmstruct to classify whether or not the detections
% are fungi according to the training data. 
function [result, scoredetect, scoreratio] = svmtest(data, svmstruct, varargin)
%% Current features are Area, Eccentricity and MeanIntensity courtesy of regionprops
    path = data.path;
    name = data.file;
    par_name = {'minratio','mindetections'};
    default_value = {0.5, 5};
    [minratio, mindetections] = parse_parameter(par_name, default_value, varargin);
    fungi_intensity_th = data.intensity_th;
    min_area = data.min_area; % minimal area for fungi in image
    % Consider increasing the minimal area. 
    im = imread([path, name]);
    % im = uint8(im);
    %% Get the sample data from the image and classify.
    [stats, ~, ~, fg_bd] = image_preprocess(im, path, name, data, varargin); % note that colorvec is now deprecated
%     %% Projection feature extraction
%     sample = [[stats.Area]', [stats.Eccentricity]', [stats.MeanIntensity]'];
%     %% Get only *boundary* curves, we don't care about holes
%     fg_bd = bwboundaries(fg_bw, 'noholes'); % noholes converges to actual # detections
%     num_curves = length(fg_bd);
    %% Classification by SVM
    if(isempty(sample))
        result = 'Negative';
        prediction = 0;
    else
        prediction = svmclassify(svmstruct, sample);
        if((sum(prediction)/length(stats) > minratio) && (sum(prediction) > mindetections))
            result = 'Positive';
        else
            result = 'Negative';
        end;
    end;
    %% If true, outline the items with colour green = positive, orange = negative, and SAVE output
    SVMCLASSOUT = true;
    if(SVMCLASSOUT)
        f = figure('Visible', 'off'); imagesc(im); axis off; hold on;
        for i = 1:num_curves
            if(prediction(i) == 0)
                plot(fg_bd{i}(:,2), fg_bd{i}(:,1), 'r', 'LineWidth', 1.5);
            else
                plot(fg_bd{i}(:,2), fg_bd{i}(:,1), 'g', 'LineWidth', 1.5);
            end;
        end;
        saveas(f, strcat(path, name, '_result.png'));
    end;
    %% Return score vals
    scoredetect = sum(prediction);
    scoreratio = scoredetect/length(prediction);
 return;